package com.example.bhservice.mailbox.controller;

import com.example.bhservice.mailbox.config.MailConfig;
import com.example.bhservice.mailbox.util.FileBO;
import com.example.bhservice.mailbox.util.MailUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 短信发送日志
 *
 * @Author: YuLong
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/mailbox")
public class MailboxController {

    /**
     * 发送邮件
     *
     * @param mailList 收件人列表
     * @return 发送结果
     */
    @PostMapping
    public String deliver(MailConfig mailConfig,FileBO fileBO, @RequestParam("mailList") List<String> mailList, MultipartFile file) {
        if (mailList == null || mailList.size() == 0) {
            return "收件人不能为空";
        }
        if (fileBO == null || file == null) {
            return "文件不能为空";
        }
        if (fileBO.getFileName() == null || fileBO.getFileName().equals("")) {
            return "文件名不能为空";
        }
        if (fileBO.getExtension() == null || fileBO.getExtension().equals("")) {
            return "文件扩展名不能为空";
        }
        List<String> finalMailList = new ArrayList<>();
        mailList.forEach(mail -> {
            try {
                String sendResult = MailUtil.send(mailConfig, fileBO, mail,file);
                if (!sendResult.equals("success")) {
                    finalMailList.add(sendResult);
                }
            } catch (Exception e) {
                log.error("发送邮件失败", e);
            }
        });
        if (finalMailList.size() == 0) {
            return "success";
        } else {
            return "邮箱：" + finalMailList + "发送失败";
        }
    }
}
